package com.meefo.meeting.aspect;

import com.meefo.meeting.common.DateTools;
import com.meefo.meeting.common.GUID2;
import com.meefo.meeting.config.Constants;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class WriteExceptionToFileLog{

    //错误日志写入指定文件
    public void logException(String methodName, String parameter, Exception exception) {
        String id = new GUID2().toString();
        FileWriter fileWriter = null;
        String projectUrl = Constants.tomcatUrl;
        if (isLinux()) {
            projectUrl = "/meeting/logs/";
        }
        File file = new File(projectUrl + "exception/" + DateTools.getServerDateTime(1) + ".txt");
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            fileWriter = new FileWriter(file, true);
            fileWriter.write("methodName : " + methodName);
            fileWriter.write("\r\n");
            fileWriter.write("parameter : " + parameter);
            fileWriter.write("\r\n");
            fileWriter.write("ExceptionId : " + id + ",time : " + DateTools.getServerDateTime(10) + " , stackTrace: " + getStackTrace(exception));
            fileWriter.write("\r\n");
            fileWriter.close();
        } catch (Exception e) {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }

    public boolean isLinux() {
        String name = System.getProperty("os.name").toLowerCase();
        if (name.contains("linux")) {
            return true;
        } else {
            return false;
        }
    }

    public String getStackTrace(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }
}
